package controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDAO;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * Creat with IntelliJ IDEA
 * Description:处理/blog路径对应的请求
 * User:WZW
 * Date:2022-08-06
 * Time:23:52
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    // 用于获取数据库中的博客列表
    private ObjectMapper objectMapper = new ObjectMapper();
    BlogDAO blogDAO = new BlogDAO();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先尝试获取到req中的blogId参数，如果该参数存在，则说明要请求博客详情
        // 否则说明请求的是博客列表

        resp.setContentType("application/json;charset=utf8");
        String param = req.getParameter("blogId");
        if (param == null) {
            // 从数据库中查询到博客列表，转成JSON 格式，然后直接返回即可
            List<Blog> blogs = blogDAO.selectAll();
            // 把blogs对象转换成JSON格式
            String respJson = objectMapper.writeValueAsString(blogs);
            resp.getWriter().write(respJson);
        } else {
            // 存在参数，获取博客详情
            int blogId = Integer.parseInt(param);
            Blog blog = blogDAO.selectOne(blogId);
            String respJson = objectMapper.writeValueAsString(blog);
            resp.getWriter().write(respJson);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        HttpSession session = req.getSession(false);
        if (session == null) {
            // 当前用户未登录，不能提交博客
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("提交博客失败！缺少必要的参数！");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 当前用户未登录，不能提交博客
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("提交博客失败！缺少必要的参数！");
            return;
        }
        // 先从请求中取出参数（标题和正文）
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if (title == null || "".equals(title) || content == null || "".equals(content)) {
            // 直接告诉客户端，请求参数不对
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("提交博客失败！缺少必要的参数！");
            return;
        }
        // 构造blog对象，把当前的信息填进去，并插入数据库中
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        try {
            blogDAO.insert(blog);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 重定向到博客列表页
        resp.sendRedirect("blog_list.html");
    }
}
